import {
  RouteRecordRaw,
  createRouter,
  createWebHistory,
  RouteLocationNormalized,
} from 'vue-router'
import { lStorage } from '@/utils/storage'
import { store } from '@/store'
import { getRoutes } from './static.js'
import NProgress from 'nprogress'
import { TabRoute } from '@/store/modules/tabs'

// 原始全局布局组件
const Layout = () =>
  import(/* webpackChunkName: "layout" */ '@/page/layout/index.vue').then(
    (m) => m.default
  )

// 静态路由
const staticRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    component: () => import('@/page/login/index.vue'),
    meta: { hidden: true, title: '登录' },
  },
  {
    path: '/',
    redirect: '/index',
  },
  {
    path: '/404',
    component: () => import('@/page/error/404.vue'),
    meta: { hidden: true, title: '404' },
  },
]

// 布局下的静态子路由
const childRoutes = [
  {
    path: '/index',
    name: 'index',
    component: () => import('@/views/index.vue'),
    meta: {
      hidden: false,
      title: '首页',
      keepAlive: true,
      icon: 'dashboard',
      hasPerm: ['viewHome'],
      affix: true,
    },
  },
]

// 合并静态路由
const routes = [
  ...staticRoutes,
  { path: '/', component: Layout, name: 'layout', children: childRoutes },
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: routes,
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // const whiteList = ['/login', '/404'] // 白名单路由
  // const token = store.useUserStore().token
  const routesStore = store.useRoutesStore()
  const tabsStore = store.useTabsStore()

  NProgress.start() // 开始进度条

  // 白名单直接放行
  // if (whiteList.includes(to.path)) {
  // 	if (token && to.path === '/login') {
  // 		return next('/index') // 已登录用户重定向到首页
  // 	}
  // 	return next()
  // }

  // 未登录用户跳转到登录页
  // if (!token) {
  // 	NProgress.done()
  // 	// 清除所有状态
  // 	store.useUserStore().clearUserData()
  // 	store.useTabsStore().clearTabs()
  // 	store.useRoutesStore().clearRoutes(router)
  // 	resetRouter()
  // 	return next('/login')
  // }

  // 动态路由加载逻辑
  if (!routesStore.routesLoaded) {
    try {
      // 加载动态路由
      const dynamicRoutes = Array.isArray(lStorage.get('WXAI_USER_ROUTES'))
        ? lStorage.get('WXAI_USER_ROUTES')
        : await getRoutes()

      await routesStore.addRoutes(dynamicRoutes, router)
      NProgress.done()

      // 直接跳转到目标路由
      return next({ ...to, replace: true })
    } catch (error) {
      console.error('Failed to load dynamic routes:', error)
      NProgress.done()
      return next('/404')
    }
  }

  // 更新 Tabs 状态
  if (!to.matched.length) {
    NProgress.done()
    return next('/404')
  }

  // 构造符合 TabRoute 类型的路由对象
  const tabRoute: TabRoute = {
    path: to.path,
    name: to.name as string,
    meta: {
      hidden: to.meta.hidden as boolean,
      title: to.meta.title as string,
      keepAlive: to.meta.keepAlive as boolean,
      icon: to.meta.icon as string,
      hasPerm: (to.meta.hasPerm as string[]) || [],
    },
  }

  tabsStore.addTab(tabRoute as any)
  tabsStore.setActiveTab(to.path)

  NProgress.done()
  next()
})

// 路由重置函数
export function resetRouter() {
  try {
    const routesStore = store.useRoutesStore()
    routesStore.clearRoutes(router)
    childRoutes.forEach((item) => {
      router.addRoute('layout', item)
    })
  } catch (error) {
    console.error('Error during router reset:', error)
  }
}

// 全局后置钩子
router.afterEach(() => {
  NProgress.done() // 结束进度条
})

// 确保路由实例在导出前完全初始化
router.isReady().catch((error) => {
  console.error('路由初始化失败:', error)
})

export default router
